<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk" v-if="deleteB" :disabled="confirmLoading">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="可购规则名称"
              hasFeedback
            >
              <a-input
                placeholder="可购规则名称"
                v-decorator="['ruleName', validatorRules.ruleName]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="可购规则类型"
              hasFeedback
            >
              <cn-dict-select-tag
                :options="{ value: 'type', label: 'dictDataDesc' }"
                :triggerChange="true"
                dictCode="type"
                v-decorator="['type',validatorRules.type]"
                placeholder="请选择规则类型"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="可购规则维度"
              hasFeedback
            >
              <cn-dict-select-tag
                :disabled="!deleteB"
                :options="{ value: 'dimension', label: 'dictDataDesc' }"
                :triggerChange="true"
                dictCode="dimension"
                v-decorator="['dimension',validatorRules.dimension]"
                placeholder="请选择规则维度"
                @change="canbuydimen"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="custLevel" v-if="addbtn !== null">
        <a-button style="margin-right: 10px;margin-bottom: 15px" @click="custSearch(addbtn)">
          {{ addbtn }}
        </a-button>
        <a-button style="margin-right: 10px;margin-bottom: 15px" @click="removeCust" v-if="deleteB">
          删除
        </a-button>
        <a-table
          ref="table"
          size="middle"
          class='Table'
          bordered
          :scroll="{
          x:'max-content'
        }"
          rowKey="id"
          :columns="addbtn == '添加经销商' ? columns:columns1"
          :dataSource="dataSource"
          :pagination="false"
          :customRow="onClickRow"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:5}"
          @change="handleTableChange"></a-table>
      </div>

      <div>
        <div>可购商品</div>
        <!--        标签页-->
        <div>
          <a-tabs :activeKey="tabNum" @change="tabsChange">
            <a-tab-pane key="a" tab="产品">
              <div class="product">
                <a-button style="margin-right: 10px;margin-bottom: 15px" @click="chosePro('nolevel')">
                  添加
                </a-button>
                <a-button v-if="deleteB" @click="delectRow('dataSource1','selectedRowKeys2','selectedRows2')">
                  删除
                </a-button>
                <a-table
                  size="middle"
                  class='Table'
                  rowKey="id"
                  bordered
                  :customRow="onClickRowCopy"
                  :scroll="{x:'max-content'}"
                  :dataSource="dataSource1"
                  :rowSelection="{selectedRowKeys: selectedRowKeys2,columnWidth:3,onChange:onSelectChanges}"
                  :columns="columns2"
                ></a-table>
              </div>
            </a-tab-pane>
            <a-tab-pane key="b" tab="产品层级" force-render>
              <div class="product">
                <a-button style="margin-right: 10px;margin-bottom: 15px" @click="chosePro('level')">
                  添加
                </a-button>
                <a-button v-if="deleteB" @click="delectRow('dataSource2','selectedRowKeys3','selectedRows3')">
                  删除
                </a-button>
                <a-table
                  size="middle"
                  class='Table'
                  rowKey="id"
                  bordered
                  :scroll="{x:'max-content'}"
                  :dataSource="dataSource2"
                  :customRow="onClickRowCopy"
                  :rowSelection="{selectedRowKeys: selectedRowKeys3, onChange: onSelectChanges2,columnWidth:3}"
                  :columns=columns3
                ></a-table>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
    </a-spin>
    <pro-chose ref="prochoose" v-bind="modalProps" @okbro="okbropro"></pro-chose>
  </a-modal>
</template>

<script>
import proChose from '@comp/cn-components/ProChose'
import { PageListMixin } from '@/mixins/PageListMixin'
import { httpAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile } from '@/utils/validate'
import { isNil } from 'lodash'
import JImageUpload from '@/components/cn-form/JImageUpload'
import chooseModal from '@/components/cn-components/ChooseModal'

import Area from '@/components/utils/Area'

export default {
  name: 'newAdd',
  mixins: [PageListMixin],
  data() {
    return {
      tabNum: 'a',
      selectedRowKeys3: [],
      selectedRowKeys2: [],
      deleteB: true,
      dataSource2: [],  //产品层级
      dataSource1: [],  //产品
      areaLinkage: '',
      province: '',
      city: '',
      area: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        ruleName: { rules: [{ required: true, message: '' }] },
        dimension: { rules: [{ required: true, message: '' }] },
        type: { rules: [{ required: true, message: '' }] },
        ruleCode: { rules: [{ required: true, message: '' }] }
      },
      addOrUpdateUrl: window._CONFIG['domianDmsURL'] + '/custProduct/saveOrUpdate',
      name: '',
      addbtn: null,
      columns: [
        {
          title: '经销商编号',
          align: 'center',
          dataIndex: 'code',
          width: 120,
          ellipsis: true
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'name',
          width: 120,
          ellipsis: true
        }
        // {
        //   title: '所属组织',
        //   align: 'center',
        //   dataIndex: 'orgName',
        //   width: 120,
        //   ellipsis: true
        // }
      ],
      columns1: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'code',
          width: 120,
          ellipsis: true
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'name',
          width: 120,
          ellipsis: true
        }
        // {
        //   title: '终端类型',
        //   align: 'center',
        //   dataIndex: 'type',
        //   width: 120,
        //   ellipsis: true
        // }
      ],
      columns2: [
        {
          title: '产品编号',
          align: 'center',
          dataIndex: 'productCode',
          width: 80,
          ellipsis: true
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'productName',
          width: 80,
          ellipsis: true
        }
      ],
      columns3: [
        {
          title: '层级编号',
          align: 'center',
          dataIndex: 'orgCode',
          width: 80,
          ellipsis: true
        },
        {
          title: '层级名称',
          align: 'center',
          dataIndex: 'name',
          width: 80,
          ellipsis: true
        }
      ],
      selectedRows2: [],
    }
  },
  components: { JTreeSelect, JAreaLinkage, JImageUpload, proChose,chooseModal },
  created() {
    // this.initAreaData()
  },
  computed: {
    modalProps() {
      return Object.assign({}, {
        name: this.name,
        rowKey: this.rowKey
      })
    }
  },
  methods: {
    tabsChange(e) {
      this.tabNum = e
    },
    onClickRowCopy(record) {
      let that = this
      return {
        on: {
          click: () => {
            if (record.typeName) {
              let keys = that.selectedRowKeys3
              if (keys.indexOf(record.id) == -1) {
                keys.push(record.id)
                this.selectedRows3.push(record)
              } else {
                keys.remove(record.id)
                this.selectedRows3.remove(record)
              }
              this.selectedRowKeys3 = keys
            } else {
              let key = that.selectedRowKeys2
              if (key.indexOf(record.id) == -1) {
                key.push(record.id)
                that.selectedRows2.push(record)
              } else {
                key.remove(record.id)
                that.selectedRows2.remove(record)
              }
              // that.selectedRowKeys2 = key
            }
          }
        }
      }
    },
    onSelectChanges(key, rows) {
      this.selectedRowKeys2 = key
      this.selectedRows2 = rows
    },
    onSelectChanges2(key, rows) {
      this.selectedRowKeys3 = key
      this.selectedRows3 = rows
    },
    kegouguize(e) {
      console.log(e.path[0].dataset.origin)
    },
    removeCust() {
      if (this.selectionRows.length == 0) {
        return
      }
      this.selectionRows.forEach(item => {
        let num = this.dataSource.indexOf(item)
        if (num !== -1) {
          this.dataSource.splice(num, 1)
        }
      })
    },
    okbropro(val, status) {
      console.log(val)
      if (status == '添加组织') {
        val.forEach(item => {
          item.code = item.orgCode|| item.code
          item.name = item.orgName|| item.name
        })
        this.dataSource = JSON.parse(JSON.stringify(val))
      }
      if (status == 'level') {
        val.forEach(item => {
          item.code = item.typeCode|| item.code
          item.name = item.typeName|| item.name
        })
        this.dataSource2 = JSON.parse(JSON.stringify(val))
      }
      if (status == '添加经销商') {
        val.forEach(item => {
          item.code = item.custCode || item.code
          item.name = item.custName || item.name
        })
        this.dataSource = JSON.parse(JSON.stringify(val))
      }
      if (status == 'nolevel') {
        val.forEach(item => {
          item.code = item.productCode|| item.code
          item.name = item.productName|| item.name
        })
        this.dataSource1 = JSON.parse(JSON.stringify(val))
      }
    },
    custSearch(word) {
      if (word == '添加经销商') {
        // this.rowKey = 'custCode'
        this.$refs.prochoose.rowKey = 'custCode'
        this.dealWithSb(this.dataSource, 'custCode')
        let formconfig = [
          {
            key: 'custCode',
            label: '经销商编号'
          },
          {
            key: 'custName',
            label: '经销商名称'
          }
        ]
        let tableconfig = {
          columns: [
            {
              title: '经销商编号',
              align: 'center',
              dataIndex: 'custCode',
              width: 120,
              ellipsis: true
            },
            {
              title: '经销商名称',
              align: 'center',
              dataIndex: 'custName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/customerController/getPageList',
          multiple: true,
          columW: 12
        }
        this.name = '经销商'
        // if (this.dataSource.length !== 0) {
        //  let array = this.dataSource.map(item =>{
        //    return item.id
        //  })
        //   this.$refs.prochoose.selectedRowKeys = array
        // }

        this.$refs.prochoose.edit(formconfig, tableconfig, word, 'keys2', this.dataSource)
      }
      if (word == '添加组织') {
        this.$refs.prochoose.rowKey = 'orgCode'
        this.dealWithSb(this.dataSource, 'orgCode')
        let formconfig = [
          {
            key: 'orgCode',
            label: '组织编号'
          },
          {
            key: 'orgName',
            label: '组织名称'
          }
        ]
        let tableconfig = {
          columns: [
            {
              title: '组织编号',
              align: 'center',
              dataIndex: 'orgCode',
              width: 120,
              ellipsis: true
            },
            {
              title: '组织名称',
              align: 'center',
              dataIndex: 'orgName',
              width: 120,
              ellipsis: true
            },
            {
              title: '组织类型',
              align: 'center',
              dataIndex: 'orgType',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnOrgController/getPageList',
          columW: 12,
          multiple: true
        }
        this.name = '组织'
        this.$refs.prochoose.edit(formconfig, tableconfig, word, 'keys2', this.dataSource)
      }

    },
    canbuydimen(e) {
      console.log(e)
      // if(typeof e == 'undefined')
      // debugger
      switch (e) {
        case '1':
          this.addbtn = '添加经销商'
          this.dataSource = []
          break
        case '2':
          this.addbtn = '添加组织'
          this.dataSource = []
          break
        case undefined:
          this.addbtn = null
          this.dataSource = []
          break
      }

      console.log(this.addbtn)
    },
    // 选择商品
    chosePro(word) {
      if (word == 'nolevel') {
        this.$refs.prochoose.rowKey = 'productCode'
        this.$refs.prochoose.isorter.ways='post'
        // this.dealWithSb(this.dataSource1, 'productCode')
        let formconfig = [
          {
            key: 'productCode',
            label: '产品编号'
          },
          {
            key: 'productName',
            label: '产品名称'
          }
        ]
        let tableconfig = {
          columns: [
            {
              title: '产品编号',
              align: 'center',
              dataIndex: 'productCode',
              width: 80,
              ellipsis: true
            },
            {
              title: '产品名称',
              align: 'center',
              dataIndex: 'productName',
              width: 80,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/goods/cnGoods/findPageList',
          columW: 12,
          multiple: true
        }
        this.name = '产品'
        this.$refs.prochoose.edit(formconfig, tableconfig, word, 'keys2', this.dataSource1)
      }
      if (word == 'level') {
        this.$refs.prochoose.rowKey = 'classifyCode'
        // this.dealWithSb(this.dataSource2, 'typeCode')
        let formconfig = [
          {
            key: 'typeLevel',
            label: '产品层级'
          },
          {
            key: 'classifyCode',
            label: '层级编号'
          }, {
            key: 'classifyName',
            label: '层级名称'
          }
        ]
        let tableconfig = {
          columns: [
            // {
            //   title: '产品层级',
            //   align: 'center',
            //   dataIndex: 'typeLevel',
            //   ellipsis: true
            // },
            {
              title: '层级编号',
              align: 'center',
              dataIndex: 'classifyCode',
              ellipsis: true
            },
            {
              title: '层级名称',
              align: 'center',
              dataIndex: 'classifyName',
              ellipsis: true
            }
          ],
          columW: 50,
          multiple: true,
          list: window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/findPageList'
        }
        this.name = '产品层级'
        this.$refs.prochoose.edit(formconfig, tableconfig, word, 'keys2', this.dataSource2)
      }
    },
    dealWithSb(arry, sb) {
      return arry.forEach(item => {
        if (!item[sb]) {
          item[sb] = item.code
        }
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.addbtn = null
      this.tabNum = 'b'
      this.tabNum = 'a'
      this.dataSource2 = []
      this.dataSource1 = []
      this.dataSource = []
      this.model = Object.assign({}, record)
      this.visible = true
      if (record) {
        this.dataSource1 = this.model.products
        this.dataSource2 = this.model.goodsLayer
      } else {
        this.deleteB = true
      }
      // 经销商、终端数组
      if (this.model.dimension == 1) {
        this.addbtn = '添加经销商'
      } else if (this.model.dimension == 2) {
        this.addbtn = '添加组织'
      }
      this.dataSource = this.model.areaes
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'ruleCode', 'ruleName', 'type', 'dimension'))
        //时间格式化
      })

    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let method = ''
          if (!this.model.id) {
            method = 'post'
          } else {
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          // this.dataSource.forEach(item => {
          //   item.type = formData.dimension
          // })
          // this.dataSource1.forEach(item => {
          //   item.type = 1
          // })
          // this.dataSource2.forEach(item => {
          //   item.type = 2
          // })
          formData.customers = this.dataSource
          // formData.products = [...this.dataSource1, ...this.dataSource2]
          formData.products = this.dataSource1
          //时间格式化
          // formData.punchTime = formData.punchTime ? formData.punchTime.format('YYYY-MM-DD HH:mm:ss') : null;
          // formData.birthday = formData.birthday ? formData.birthday.format() : null;

          // console.log(formData)
          httpAction(this.addOrUpdateUrl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    areaChange(code) {
      this.model.province = this.areaData.getText(code).split('/')[0]
      this.model.city = this.areaData.getText(code).split('/')[1]
      this.model.area = this.areaData.getText(code).split('/')[2]
    }
    // initAreaData() {
    //   if (!this.areaData) {
    //     this.areaData = new Area()
    //   }
    // }
  }
}
</script>

<style scoped>
.product {
  padding: 10px 50px 0;
}

.custLevel {
  margin: 10px 0 15px 0;
}
</style>